import React, { Component } from 'react'
import {Button,Row, Col, Divider} from 'antd'
import PubSub from 'pubsub-js'
import flvjs from 'flv.js'
import './index.scss'
import {createWebSocket,closeWebSocket,websocket} from '../../utils/websocket'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
// 引入api
import {detectCurFrame} from '../../api/video'
// 引入工具类
import {createFormData} from '../../utils/creatFormData'
// let boxpool = [[0.5966184139251709, 0.49981042742729187, 0.6493131518363953, 0.6164175868034363], [0.2250565141439438, 0.8328591585159302, 0.26245325803756714, 0.9108520150184631]];
// let namedboxpool = ['ysx','zlf'];
let boxpool = [];
let namedboxpool = [];
let imageUrl = "";
let detect = "";
const style = { background: '#fff', padding: '0px 14px' };
export default class Play extends Component {
    state ={       
        imageUrl:"",
        stream_name:'',
        time1:'',
        user_id:'',
        filename:''
    }

    togglelist = ()=>{
        this.props.switchForm('list')
    }

    start = ($video,filename) => {
        if($video){
            if (flvjs.isSupported()) {
                // console.log("sdgfj")
                let flvPlayer = flvjs.createPlayer({
                                    type: 'flv',
                                    isLive: true,
                                    cors: true,
                                    // url: `http://10.138.91.196/live?port=1935&app=live&stream=${stream_name}`,
                                    // url:'http://120.27.241.217/livestreamk-1616722889.flv',
                                    url:`http://www.dpl402.site:2180/${filename}`,
                                    // url:'http://10.138.71.57/2.mp4',
                                    // url: `http://58.200.131.2/livetv?port=1935&app=livetv&stream=cctv1`,
                                    // url: 'http://120.27.241.21/rtmp/records/livestream-1615514859.flv',
                                    duration: 0,
                                }, {
                                    enableStashBuffer: false,
                                    isLive: true,
                                    lazyLoad: false,
                                    lazyLoadMaxDuration: 0,
                                    lazyLoadRecoverDuration: 0,
                                    deferLoadAfterSourceOpen: false,
                                    fixAudioTimestampGap: false,
                                }
                            );
                            flvPlayer.attachMediaElement($video);
                            flvPlayer.load(); //加载
                            flvPlayer.play();
                            this.flvPlayer = flvPlayer;             
            }
        }
        
    }
    draw = (ctx,boxes,id,width,height) => { 
        // console.log(boxes,id)
        let i = 0      
        while(boxes.length > 0 && i<boxes.length){
            // var box = new Array(boxes[i])
            let box = new Array(boxes[i])
            // console.log(box)
            var na = id[i]
            let aa = new Array(box);
            let a = aa[0][0]
            // console.log('x,y,w,h',a[0],a[1],a[2],a[3])
            // console.log(i)
            // console.log('a',a)
            ctx.fillStyle = "rgba(255, 0, 0, 0.3)";
            ctx.fillRect(a[0]*width, a[1]*height, a[2]*width-a[0]*width, a[3]*height-a[1]*height);
            ctx.font="25px Arial";
            ctx.strokeRect(a[0]*width, a[1]*height, a[2]*width-a[0]*width, a[3]*height-a[1]*height);
            ctx.fillText(na, a[0]*width, a[1]*height+16);
            i+=1
        }       
    }

    toCanvas = ()=>{
        var canvas = document.getElementById('c1');
        var video = document.getElementById('videoElement')
        // console.log(video)
        // this.cut()
        if(detect === "right"){
            this.right_detect()
        }
        
        if(canvas){
            var context = canvas.getContext("2d");
            context.drawImage(video, 0, 0, canvas.width, canvas.height);//绘制视频
            this.draw(context,boxpool,namedboxpool,canvas.width,canvas.height)
        } 
        this.aFrameId=window.requestAnimationFrame(this.toCanvas)
    }

    componentDidMount(){
        this.token = PubSub.subscribe('str_list',(_,data)=>{
            this.setState(data)  
            const {filename} = data
            console.log("第一次接受的data",data)
            console.log('发布llllll',filename)          
        })
        let url=`ws://127.0.0.1:8080/ws/ws_2_3`;//服务端连接的url
        this.websocket = createWebSocket(url)
        this.websocket.onmessage =  (event)=>{          
            // console.log("video中的data",event.data)
            if(event.data==='null'||event.data === `{"msg": "ready"}`||event.data==='{}'){  
                // console.log('if里的id',this.state.id)   
                namedboxpool = []
                boxpool = []          
            }else{   
                // console.log('event.data为：', event.data)            
                const {id,box}=JSON.parse(event.data)
                // this.id = id
                // this.box = box
                // console.log('从后台得到的人脸数据',id,box)
                namedboxpool = id
                boxpool = box              
            }                                
        } 
        // this.setState({})
        this.toCanvas()
    }

    dataURLtoFile = (dataurl,filename) => { 
        // console.log('图片地址为：',dataurl)
        // console.log('图片名称',filename)
	    var arr = dataurl.split(','),
	        mime = arr[0].match(/:(.*?);/)[1],
	        bstr = atob(arr[1]),
	        n = bstr.length,
	        u8arr = new Uint8Array(n);
	    while (n--) {
	        u8arr[n] = bstr.charCodeAt(n);
	    }
	    return new File([u8arr], filename, { type: mime });
    }

    change_detect = ()=>{
        if(detect === ""){
            detect="right"
        }else{
            detect=""
            namedboxpool = []
            boxpool = []
        }   
    }
    
    right_detect = ()=>{
        
        var canvas = document.getElementById('c1');
        var context = canvas.getContext("2d");
        imageUrl=context.canvas.toDataURL();
        // console.log(imageUrl)
        var na = 'sfsdf'
        var file = this.dataURLtoFile(imageUrl,na)
        if (this.websocket.readyState===1) {
            this.websocket.send(file)
        }
    }

    cut = ()=>{   
        // setTimeout(() =>{
        //     var canvas = document.getElementById('c1');
        // var context = canvas.getContext("2d");
        // imageUrl=context.canvas.toDataURL();
        // console.log(imageUrl)
        // var na = 'sfsdf'
        //         var file = this.dataURLtoFile(imageUrl,na)
        //         console.log('截取的图片文件为:',file)
        //         let sailorData={}
        //         sailorData.file=file
        //         if(file){
        //             detectCurFrame(createFormData(sailorData)).then(response => {
        //                 console.log(response.data)           
        //                 if(JSON.stringify(response.data) === "{}"){
        //                     namedboxpool = []
        //                     boxpool = []
        //                 }else{
        //                     const {id,box} = response.data
        //                     // this.id = id
        //                     // this.box = box
        //                     console.log('从后台得到的人脸数据',id,box)
        //                     namedboxpool = id
        //                     boxpool = box
        //                     this.toCanvas()
        //                 }
        //             }).catch(error => {
        //                 console.log(error)
        //                 // alert("上传图片失败")
        //             })
        //         }
        //         else{
        //             alert("您还未上传图片");
        //         }
        // }, 16);    
        var canvas = document.getElementById('c1');
        var context = canvas.getContext("2d");
        imageUrl=context.canvas.toDataURL();
        // console.log(imageUrl)
        var na = 'sfsdf'
                var file = this.dataURLtoFile(imageUrl,na)
                console.log('截取的图片文件为:',file)
                let sailorData={}
                sailorData.file=file
                if(file){
                    detectCurFrame(createFormData(sailorData)).then(response => {
                        console.log(response.data)           
                        if(JSON.stringify(response.data) === "{}"){
                            namedboxpool = []
                            boxpool = []
                        }else{
                            const {id,box} = response.data
                            // this.id = id
                            // this.box = box
                            console.log('从后台得到的人脸数据',id,box)
                            namedboxpool = id
                            boxpool = box
                            this.toCanvas()
                        }
                    }).catch(error => {
                        console.log(error)
                        // alert("上传图片失败")
                    })
                }
                else{
                    alert("您还未上传图片");
                }
    }


    componentWillUnmount(){
        if (this.flvPlayer) {
            this.flvPlayer.unload();
            this.flvPlayer.detachMediaElement();
        }
        window.cancelAnimationFrame(this.aFrameId)
        this.aFrameId = null
        boxpool = []; 
        namedboxpool = [];
        this.websocket.close()

    }

    render() {
        // const {filename} = this.state
        // PubSub.subscribe('str_list',(_,data)=>{
        //     // this.setState(data)  
        //     const {filename} = data
        //     console.log('fgg',filename)
        //     // console.log('发布llllll',filename)          
        // })
        const {stream_name:kkkk} = this.props
        // console.log(kkkk)
        const {stream_name,time1,time2,user_id,filename} = kkkk
        console.log(stream_name,time1,time2,user_id,filename)
        // console.log(stream_name)
        // console.log("流名:",this.state.stream_name,"id:",this.state.id)
        return (
            <div className="styleOkj">
                    {/* <div className="info"> */}
                    <Divider orientation="left">执法记录信息</Divider>
                    <Row >
                    <Col className="gutter-row" span={4}>
                        <div style={style}><h2><strong>流名</strong>：{stream_name}</h2></div>
                    </Col>
                    <Col className="gutter-row" span={4}>
                        <div style={style}><h2><strong>推流人:</strong> {user_id}</h2></div>
                    </Col>
                    <Col className="gutter-row" span={10}>
                        <div style={style}><h2><strong>推流时间：</strong>{time2}</h2></div>
                    </Col>
                    </Row>                    
                    {/* </div>                   */}
                    <br/>
                    <div className="videos">
                    <video style={{backgroundColor:'black'}} ref={(c)=>{this.start(c,filename)}} crossOrigin="Anonymous" name="videoElement" id="videoElement" className="centerVideo" controls muted autoPlay width="400"
                        height="200">
                        Your browser is too old which doesn't support HTML5 video.                          
                    </video>&nbsp;
                    {/* <canvas style={{border:'1px solid #d3d3d3'}} ref={this.canvas_dispaly} id="c1" width="600" height="500"/> */}
                    <canvas style={{border:'1px solid #d3d3d3'}} ref={this.canvas_dispaly} id="c1" width="590" height="375"/>
                    </div>
                    
                    <br/>
                    <br/>
                    <Button className="butt" onClick={this.togglelist}>返回列表</Button>&nbsp;&nbsp;&nbsp;
                    <Button onClick={this.cut}>点击检测</Button>
                    {/* <Button onClick={this.change_detect}>实时检测</Button>                     */}
            </div>
        )
    }
}
